/**
 * Created by leo on 10/28.
 */
(function () {
    'use strict';
    angular.module('Tab', ['commons'])
        .factory('tabService', function ($window, titlePrefix, $http, urlPrefix, urlMap) {
            var tabs = [
                {id: (Date.now() + Math.random()).toString(36), name: '首页', url: 'portal.html'}
            ], activeTab = 0, tabSwitchedListeners = [];
            return {
                hasTabs: function () {
                    return tabs.length > 1;
                },
                getTabs: function () {
                    return tabs;
                },
                addTab: function (tab) {
                    if (tab.url == "#home") {
                        this.activeTab(0);
                        return;
                    }
                    for (var i = 1; i < tabs.length; i++) {
                        if (tabs[i].name == tab.name) {
                            if (tabs[i].url != tab.url) {
                                tabs[i].url = tab.url;
                            }
                            this.activeTab(i);
                            return;
                        }
                    }
                    if (tab.name && tab.url) {
                        tab.initName = tab.name; // tab创建时的名字,在页面刷新返回后可以恢复原始名字
                        this.activeTab(tabs.push(tab) - 1);
                        tab.id = (Date.now() + Math.random()).toString(36);
                        tabs[tab.id] = tab;
                        $window.scrollTo(0, 0);
                    }
                    var url = urlMap[tab.url.replace(/[&?]0\.[a-z0-9]+$/, '')];
                    if (url) $http.post(urlPrefix + "/ibnms/report/addModuleUseLog.action", '', {params: {path: url}});
                },
                activeTab: function (index) {
                    // 无参时直接返回activeTab的值，有参的话修改activeTab的值
                    var oldActiveTab = activeTab;
                    if (!isNaN(index) && tabs[index] != undefined) {
                        activeTab = index;
                        $window.document.title = titlePrefix + tabs[activeTab].name;
                        angular.forEach(tabSwitchedListeners, function (callback) {
                            callback(tabs[activeTab], tabs[oldActiveTab]);
                        });
                    }
                    angular.element($window).resize(); // 解决切换tab页后首页面板的图表展示异常的问题（resize后可自动恢复）
                    return oldActiveTab;
                },
                removeTab: function (index) {
                    if (index) tabs.splice(index, 1);
                    this.activeTab(activeTab >= tabs.length ? tabs.length - 1 : activeTab);
                },
                currentTab: function () {
                    return tabs[activeTab];
                },
                onTabSwitched: function (callback) {
                    tabSwitchedListeners.push(callback);
                }
            };
        })
        .directive('tabStrip', function (tabService, $window, $log, urlPrefix) {
            return {
                restrict: 'A',
                scope: {},
                link: function (scope, elem) {
                    scope.tabService = tabService;
                    var offsetTop = 0;
                    scope.getHeight = function (tab) {
                        if (!offsetTop) { // offsetTop只需要获取一次即可
                            offsetTop = elem.find('iframe:visible')[0].offsetTop
                        }
                        return $window.document.documentElement.clientHeight - offsetTop - 4;
                    };
                    scope.getTabUrl = function (tab) {
                        if (tab.url.match(/^(https?:\/\/)|(\/)/)) { // 绝对路径
                            return tab.url;
                        } else { // 相对路径
                            return urlPrefix + tab.url;
                        }
                    };
                    scope.closeTab = function(){
                        tabService.removeTab(tabService.contextMenuOpenedOn);
                        tabService.contextMenuOpened=false;
                    };
                    scope.closeOtherTab = function(){
                        var length = tabService.getTabs().length;
                        for (var i = 1; i < length; i++) {
                            if (i < tabService.contextMenuOpenedOn) {
                                tabService.removeTab(1);
                            } else if (i > tabService.contextMenuOpenedOn) {
                                tabService.removeTab(2);
                            }
                        }
                        tabService.contextMenuOpened=false;
                    };
                    scope.closeAllTab = function(){
                        var length = tabService.getTabs().length;
                        for(var i=1;i<length;i++)tabService.removeTab(1);
                        tabService.contextMenuOpened=false;
                    };
                    scope.refreshTab = function(){
                        angular.forEach(tabService.getTabs(), function (n,i) {
                            if (tabService.contextMenuOpenedOn==i) {
                                if(n.url.indexOf("randomArg")>-1){
                                    n.url=n.url.split("randomArg")[0]+"randomArg="+Math.random();
                                }else{
                                    if(n.url.indexOf("?")>-1){
                                        n.url=n.url+"&randomArg="+Math.random();
                                    }else{
                                        n.url=n.url+"?randomArg="+Math.random();
                                    }
                                }
                            }
                        })
                    }
                },
                replace: true,
                templateUrl: 'app/tab/tab-strip.html'
            };
        })
        .directive('contextMenu', function (tabService, $document) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    element.on("contextmenu", function () {
                        var actualLeft = this.offsetLeft;
                        var actualTop = this.offsetTop;
                        var current = this.offsetParent;
                        while (current !== null){
                            actualLeft += current.offsetLeft;
                            actualTop += current.offsetTop;
                            current = current.offsetParent;
                        }
                        var menuElement = angular.element(document.getElementById("contextMenu"));
                        menuElement.css('top', (actualTop+this.offsetHeight-13)+ 'px');
                        menuElement.css('left',(actualLeft+this.offsetWidth/2)+ 'px');
                        var tabIndex = element.data('index');
                        if (tabIndex > 0) {
                            tabService.contextMenuOpened = true;
                            tabService.contextMenuOpenedOn = tabIndex
                            angular.element($document).one('click', function () {
                                tabService.contextMenuOpened = false;
                                scope.$apply();
                            });
                            scope.$apply();
                        }
                        return false;
                    });
                }
            };
        });

}());